<?php
declare (strict_types = 1);

namespace app\share\controller;

use app\common\model\Token;
use app\common\model\UserLog;
use DigitalSignature\DigitalSignature;
use think\App;
use think\facade\Request;


/**
 * 控制器基础类
 */
abstract class BaseController
{
    #参数数组
    protected $data;
    #前端传递过来的sign
    protected $html_sign;
    #应用实例
    protected $app;
    #应用模块
    protected $group = '';
    #控制器
    protected $controller = '';
    #方法
    protected $action = '';
    #当前路由
    protected $routeUri = '';
    #不验证登陆白名单
    protected $allowAllActionLogin = [
        'index/test',
    ];
    #不验证签名的白名单
    protected $allowAllActionSign =[
        'index/test',
    ];


    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        #实例化token类
        $this->token = new Token();
        // 控制器初始化
        $this->initialize();
    }

    #初始化控制器
    protected function initialize()
    {
        #当前路由信息
        self::getRouteInfo();

        #签名验证
        if( !in_array( $this->routeUri, $this->allowAllActionSign ) )
        {
            #不在登录白名单的控制器\方法, 需要验证登陆token
            $data = Request::param();
            $this->html_sign = Request::header('sign');
            $data['request_method'] = Request::method();
            $data['timestamp'] = Request::header('timestamp');
            $this->data = $data;
            #实例化签名类
            $signObj = new DigitalSignature($this->data,$this->html_sign);
//            $signObj->checkSign();
        }

        #登录验证
        if( !in_array( $this->routeUri, $this->allowAllActionLogin ) )
        {
            #不在登录白名单的控制器\方法, 需要验证登陆token
            $token = Request::header('token');
            #token验证
//            $this->token->checkToken($token);
            #后台登录后操作日志,登录日志在登陆成功之后写入
            $data['method']      = $this->routeUri;
            $data['user_id']     = getTokenId($token);
            $data['create_time'] = time();
            $data['ip']          = Request::ip();
            #实例化日志类,写入访问日志表
            $log = new UserLog();
//            $log->writeLog($data);
        }
    }
    /**
     *获取当前模块,控制器,方法
     */
    private function getRouteInfo()
    {
        #模块
        $this->group = App('http')->getName();
        #控制器名称 驼峰命名转下划线命名
        $this->controller = toUnderScore(Request()->controller());
        #方法名称
        $this->action = Request()->action();
        #当前route
        $this->routeUri = $this->controller."/".$this->action;
    }



}
